// pages/cart/cart.js
import { Cart } from 'cart-model.js'
var cart = new Cart();
//获取应用实例
const app = getApp()

Page({
  data: {
    userInfo: null,
    loadEnd: false,
    allProducts: null,
    delBtnWidth: 100,//删除按钮宽度单位（rpx）
    showProductDetail: false,
    showGoodsDetail: null,
    oldGoodsDetail: null,//旧商品信息，包括size和id
    // 弹窗出来需要的数据
    nowSelGoods: {
      nowSelTotal: '',//当前选中商品要购买的数量
      leaveNum: '',//剩余商品数量
      color: '',
      size: '',
    },
    dialogAddFalse: false,// 弹窗加减disabled
    dialogReduceFalse: false, // 弹窗加减disabled
    allCheckedStatus: false, // 全选
    totalPay: '',//应付款总额（选中的项）
    isShowPopup: false,//是否显示弹窗
    tip: "",//弹窗显示内容
    netWorkTimeOut: false,//网络请求超时
  },
  onLoad: function (options) {
    this.initData()
  },
  onShow() {
    let loginClose = wx.getStorageSync('loginClose');
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo
    });
    if (!userInfo && !loginClose) {

      wx.navigateTo({
        url: '/pages/login/login'
      })
    }
    this.initData()
  },
  //初始化数据封装
  initData(callback, type) {
    let userInfo = wx.getStorageSync('userInfo')
    let data = this.data
    let pay = 0
    let sum = 0
    if (userInfo && userInfo != "") {
      this.setData({
        userInfo: userInfo,
      })
      let params = {
        "data": {
          "userId": '' + userInfo.id,
          "storeNo": userInfo.storeNo
        }
      }
      if (!(type || type == 'pulldown')) {
        wx.showLoading({
          title: '加载中',
        })
      }
      cart.getCart(params, res => {
        if (res.status) {
          let newArray = []
          let unity = app.globalData.unity;

          console.log("unity------------------------", unity);
          res.data.forEach(val => {
            val.checked = false
            val.txtStyle = ''
            val.addFalse = false
            val.reduceFalse = false

            // 判断是否选中过
            let id = val.goodsId;
            let specsName = val.specsName;

            for (let i in unity) {
              let thatId = unity[i].id;
              let thatSpecsName = unity[i].specsName;
              if (thatId == id && thatSpecsName == specsName) {
                val.checked = true;
              }
            }

            newArray.push(val)
          })


          this.setData({
            allProducts: newArray,
            loadEnd: true,
            netWorkTimeOut: false
          })
          // 计算总价
          console.log(newArray)
          newArray.forEach((val, i) => {
            if (val.checked) {
              console.log(+val.goodsPrice * +val.goodsNum)
              pay += +val.goodsPrice * +val.goodsNum
              sum += val.goodsNum
            }
          })
          this.setData({
            totalPay: this.returnFloat(pay),
            totalSum: sum
          })
          newArray.forEach(val => {
            if (!val.checked) {
              this.setData({
                allCheckedStatus: false
              })
              return
            }
          });

          this.getProductCount();
          wx.hideLoading()
          callback && callback()
        } else {
          console.log("请求服务器错误!")
          wx.hideLoading()
          this.setData({
            netWorkTimeOut: true
          })
          cart.showMyTip({ _this: this, title: "服务器错误" })

        }
      })

    }

  },
  //列表增加
  add(e) {
    let id = cart.getDataSet(e, "id")
    let index = cart.getDataSet(e, "index")

    this.addReduceCommon('add', id, index)
    this.getProductCount();
  },
  //列表减少
  reduce(e) {
    let id = cart.getDataSet(e, "id")
    let index = cart.getDataSet(e, "index")
    this.addReduceCommon('reduce', id, index)
    this.getProductCount();
  },
  // 列表页增加减少请求封装
  addReduceCommon: function (type, id, index) {
    let allProducts = this.data.allProducts
    let userInfo = this.data.userInfo
    let nowGoods = null
    console.log(type, id)
    let val = allProducts[index]
    console.log('val', val)
    if (type == 'add') {
      if (val.stockNum > val.goodsNum) {
        wx.showLoading({
          title: '加载中'
        })
        val.addFalse = false
        val.reduceFalse = false
        val.goodsNum++
      } else {
        val.addFalse = true
        val.reduceFalse = false
      }
    } else {
      if (val.goodsNum == 1) {
        val.reduceFalse = true
        val.addFalse = false
      } else {
        wx.showLoading({
          title: '加载中'
        })
        val.reduceFalse = false
        val.addFalse = false
        val.goodsNum--
      }
    }
    nowGoods = {
      "data": {
        "userId": "" + userInfo.id,
        "storeNo": "" + userInfo.storeNo,
        "goodsId": "" + id,
        "specsName": "" + val.specsName,
        "goodsName": "" + val.goodsName,
        "goodsNum": "" + val.goodsNum,
        "goodsPrice": "" + val.goodsPrice,
        "originalPrice": "" + val.goodsPrice,
        "goodsColor": "" + val.goodsColor,
        "goodsPic": "" + val.goodsPic,
        "oldGoodsId": "" + id,
        "oldSpecsName": "" + val.specsName
      }
    }
    cart.upadateCart(nowGoods, res => {
      if (res.status) {
        wx.hideLoading()
        let pay = 0
        let sum = 0
        this.data.allProducts.forEach((val, i) => {
          if (val.checked) {
            pay += +val.goodsPrice * +val.goodsNum
            sum += val.goodsNum
          }
        })
        this.setData({
          totalPay: this.returnFloat(pay),
          allProducts: allProducts,
          totalSum: sum
        })
      } else {
        wx.hideLoading()
        cart.showMyTip({ _this: this, title: "服务器错误" })
      }
    })
  },
  // 删除商品
  deleteGoods(e) {
    console.log(cart.getDataSet(e, "id"), cart.getDataSet(e, 'specsname'))
    var that = this
    let userInfo = this.data.userInfo
    let pay = 0;
    let sum = 0
    let params = {
      "data": {
        "userId": "" + userInfo.id,
        "storeNo": "" + userInfo.storeNo,
        "goodsId": "" + cart.getDataSet(e, "id"),
        "specsName": "" + cart.getDataSet(e, 'specsname')
      }
    }
    wx.showModal({
      title: '提示',
      content: '确认删除吗？',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          cart.deleteCart(params, res => {
            wx.hideLoading()
            console.log(res)
            let status = res.status
            if (status) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 1500,
                success() {
                  setTimeout(() => {
                    that.initData(() => {
                      that.data.allProducts && that.data.allProducts.forEach((val, i) => {
                        if (val.checked) {
                          pay += +val.goodsPrice * +val.goodsNum
                          sum += val.goodsNum
                        }
                      })
                      that.setData({
                        totalPay: that.returnFloat(pay),
                        totalSum: sum
                      })
                    });
                  }, 1000)
                }
              })
            } else {
              wx.hideLoading()
              cart.showMyTip({ _this: this, title: "服务器错误" })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 单个checkbox选中操作
  checkboxChange(e) {
    let index = cart.getDataSet(e, "index");
    var item = "allProducts[" + index + "].checked";
    let that = this;
    let data = this.data
    var id = data.allProducts[index].goodsId;
    var specsName = data.allProducts[index].specsName;
    var change = data.allProducts[index].checked ? false : true;
    this.setData({
      [item]: change
    })
    if (change) {
      this.unity(id, specsName);
    } else {
      this.difference(id, specsName);
    }


    let pay = 0,
      allCheckedStatus,
      length = 0,
      sum = 0;
    data.allProducts && data.allProducts.forEach((val, i) => {
      if (val.checked) {
        pay += +val.goodsPrice * +val.goodsNum
        sum += val.goodsNum
        length++
      } else {
        allCheckedStatus = false
      }
      if (data.allProducts.length == length) {
        allCheckedStatus = true
      }
    })
    this.setData({
      totalPay: that.returnFloat(pay),
      allCheckedStatus: allCheckedStatus,
      totalSum: sum
    })
    // console.log(this.data.allProducts, pay);
  },
  //取消选中
  difference(id, specsName) {
    let unity = app.globalData.unity;
    for (let i in unity) {
      let thatId = unity[i].id;
      let thatSpecsName = unity[i].specsName;
      if (thatId == id && thatSpecsName == specsName) {
        unity.splice(i, 1);
      }
    }
    console.log("globalData-------------", app.globalData.unity);
  },
  //选中
  unity(id, specsName) {
    let unity = app.globalData.unity;
    let ids = new Set();
    for (let i in unity) {
      ids.add(unity[i].id);
    }
    let setIds = Array.from(ids);
    console.log("setIds--------------", setIds);

    if (unity.length > 0) {
      for (let i in unity) {

        let thatId = unity[i].id;
        let tahtSpecsName = unity[i].specsName;

        if (setIds.indexOf(id) != -1) {
          if (thatId == id && specsName != tahtSpecsName) {
            unity.push({ "id": id, "specsName": specsName });
            break;
          }
        } else {
          unity.push({ "id": id, "specsName": specsName });
          break;
        }

      }
    } else {
      unity.push({ "id": id, "specsName": specsName });
    }

    console.log("unity------------------------", unity);
  },
  //计算商品选择数量
  getProductCount() {
    let allProducts = this.data.allProducts;
    let crtNum = 0;
    allProducts.forEach(val => {
      crtNum += parseInt(val.goodsNum);
    })
    //设置购物车右上角红色点
    wx.setTabBarBadge({
      index: 1,
      text: '' + crtNum,
    })
  },
  //去付款
  onOrderConfirme() {
    let userInfo = this.data.userInfo
    let allProducts = this.data.allProducts
    let result = []
    let that = this
    allProducts.forEach(val => {
      if (val.checked) {
        result.push({
          "goodsId": "" + val.goodsId,
          "specsName": val.specsName,
          "storeNo": "" + userInfo.storeNo,
          "userId": "" + userInfo.id,
        })
      }
    })

    let params = {
      "data": {
        "list": result
      }
    }
    if (result.length <= 0) {
      cart.showMyTip({ _this: this, title: "您还没有选择宝贝哦！" })
      return
    }
    cart.createOrderAndDetails(params, res => {
      if (res.status) {
        app.globalData.unity.length = 0;
        that.setData({
          allCheckedStatus: false
        })
        wx.navigateTo({
          url: "/pages/orderDetail/orderDetail?orderId=" + res.data.orderId
        })
      } else {
        cart.showMyTip({ _this: this, title: "服务器错误" })
      }
    })

  },
  touchS: function (e) {
    this.closeAll()
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，文本层位置不变
        txtStyle = "left:0rpx";
      } else if (disX > 0) {//移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "rpx";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "rpx";
        }
      }
      //获取手指触摸的是哪一项
      var index = cart.getDataSet(e, "index");
      var allProducts = this.data.allProducts;
      allProducts[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        allProducts: allProducts
      });
    }
  },
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "rpx" : "left:0rpx";
      //获取手指触摸的是哪一项
      var index = cart.getDataSet(e, "index");;
      var allProducts = this.data.allProducts;
      allProducts[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        allProducts: allProducts
      });
    }
  },
  closeAll(e) {
    let all = []
    this.data.allProducts.forEach((val) => {
      val.txtStyle = 'left:0'
      all.push(val)
    })
    this.setData({
      allProducts: all
    });
  },
  onProductDetail(e) {
    let productDetail = this.data.showProductDetail;
    let id = cart.getDataSet(e, "id")
    let num = cart.getDataSet(e, "num")
    let size = cart.getDataSet(e, "size")
    let color = cart.getDataSet(e, "color")
    this.selColorChange(id, res => {
      this.setData({
        'showGoodsDetail': res.data,
      })
      this.data.showGoodsDetail.goodsStock.forEach((val, i) => {
        if (val.specsName == size) {
          this.setData({
            'nowSelGoods': {
              nowSelTotal: num,//当前选中商品要购买的数量
              leaveNum: val.stockNum,//剩余商品数量
              color: color,
              size: size,
            },
            oldGoodsDetail: {
              size: size,
              id: id
            }
          })
          if (val.stockNum <= num) {
            this.setData({
              'dialogAddFalse': true,
            })
          } else {
            this.setData({
              'dialogAddFalse': false,
            })
          }
        }
      })
    })
    this.setData({
      showProductDetail: productDetail ? false : true
    })
  },
  // 弹出层添加按钮
  dialogAdd(e) {
    let nowSelGoods = this.data.nowSelGoods
    let total = nowSelGoods.nowSelTotal
    let leave = nowSelGoods.leaveNum
    let oldGoodsSize = this.data.oldGoodsDetail.size;
    let storkNum = 0; //可添加商品数量
    let id = cart.getDataSet(e, "id");
    let goodsNum = 0;
    total++

    this.data.allProducts.forEach((value, i) => {
      if (value.goodsId == id && value.specsName == nowSelGoods.size) {
        goodsNum = value.goodsNum;
      }
    })

    if (oldGoodsSize == nowSelGoods.size) {
      storkNum = leave;
    } else {
      storkNum = (leave - goodsNum) < 0 ? 0 : (leave - goodsNum);
    }

    if (storkNum <= total) {
      this.setData({
        'dialogAddFalse': true,
        'dialogReduceFalse': false,
        'nowSelGoods.nowSelTotal': total,
      })
    } else if (leave > total) {
      this.setData({
        'nowSelGoods.nowSelTotal': total,
        'dialogReduceFalse': false,
        'dialogAddFalse': false,
      })
    }
  },
  dialogReduce() {
    let nowSelGoods = this.data.nowSelGoods
    let total = nowSelGoods.nowSelTotal
    let leave = nowSelGoods.leaveNum
    total--
    if (total == 1) {
      this.setData({
        'dialogReduceFalse': true,
        'dialogAddFalse': false,
        'nowSelGoods.nowSelTotal': total,
      })
    } else if (total > 0) {
      this.setData({
        'nowSelGoods.nowSelTotal': total,
        'dialogAddFalse': false,
        'dialogReduceFalse': false,

      })

    }
  },
  // 切换颜色
  toggleColor(e) {
    let userInfo = this.data.userInfo
    let color = cart.getDataSet(e, "color")
    let id = cart.getDataSet(e, "id")
    let curId = this.data.showGoodsDetail.goodsId;
    if (id != curId) {
      let params = {
        "data": {
          "storeNo": userInfo.storeNo,
          "goodsId": "" + id
        }
      }
      this.selColorChange(id, res => {
        this.setData({
          'dialogAddFalse': true,
          'dialogReduceFalse': true,
          'showGoodsDetail': res.data,
          'nowSelGoods.color': color,
          'nowSelGoods.size': '',
          'nowSelGoods.leaveNum': '',
        })
      })
    }
  },
  //   切换size
  toggleSize(e) {
    let userInfo = this.data.userInfo
    let num = cart.getDataSet(e, "num")
    let size = cart.getDataSet(e, "size")
    let nowSelSize = this.data.nowSelGoods.size;
    let oldGoodsSize = this.data.oldGoodsDetail.size;
    let id = this.data.showGoodsDetail.goodsId;
    let storkNum = 0;//商品总数量
    let goodsNum = 0;//购物车内商品数量
    this.data.allProducts.forEach((value, i) => {
      if (value.goodsId == id && value.specsName == size) {
        goodsNum = value.goodsNum;
      }
    })

    this.data.showGoodsDetail.goodsStock.forEach((val, i) => {
      if (val.specsName == size) {
        if (nowSelSize == size) {
          this.setData({
            'nowSelGoods.size': '',
            'nowSelGoods.leaveNum': ''
          })
        } else {
          this.setData({
            'nowSelGoods.size': size,
            'nowSelGoods.leaveNum': val.stockNum,
            'dialogReduceFalse': false,
            'dialogAddFalse': false
          })
        }

        //数量新增需要删除当前购物车数量
        if (oldGoodsSize == size) {
          storkNum = val.stockNum;
        } else {
          storkNum = (val.stockNum - goodsNum) < 0 ? 0 : (val.stockNum - goodsNum);
        }

        if (storkNum <= this.data.nowSelGoods.nowSelTotal) {
          this.setData({
            'dialogAddFalse': true,
            'dialogReduceFalse': false,
            'nowSelGoods.nowSelTotal': storkNum
          })
        }

      }
    })
  },
  // 封装选择商品获取商品详情
  selColorChange(id, callback) {
    let userInfo = this.data.userInfo
    let params = {
      "data": {
        "storeNo": userInfo.storeNo,
        "goodsId": "" + id
      }
    }
    cart.getGoodsById(params, res => {
      if (res.status) {
        callback && callback(res)
      }
    })
  },
  //   保存修改
  submitChange() {
    let that = this
    let data = this.data
    let userInfo = data.userInfo
    let showGoodsDetail = data.showGoodsDetail
    let oldGoodsDetail = data.oldGoodsDetail
    let nowSelGoods = data.nowSelGoods

    if (nowSelGoods.size == "") {
      cart.showMyTip({ _this: that, title: "请选择尺寸" })
      return;
    }
    if (nowSelGoods.nowSelTotal <= 0) {
      cart.showMyTip({ _this: that, title: "请添加商品数量" })
      return;
    }

    let params = {
      "data": {
        "userId": '' + userInfo.id,
        "storeNo": userInfo.storeNo,
        "goodsId": '' + showGoodsDetail.goodsId,
        "specsName": nowSelGoods.size,
        "goodsName": showGoodsDetail.goodsName,
        "goodsNum": '' + nowSelGoods.nowSelTotal,
        "goodsPrice": '' + showGoodsDetail.discountPrice,
        "originalPrice": '' + showGoodsDetail.goodsPrice,
        "goodsColor": nowSelGoods.color,
        "goodsPic": showGoodsDetail.goodsPic,
        "oldGoodsId": '' + oldGoodsDetail.id,
        "oldSpecsName": oldGoodsDetail.size
      }
    }
    console.log(params)
    wx.showModal({
      title: '提示',
      content: '确认保存吗？',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          cart.upadateCart(params, res => {
            if (res.status) {
              wx.hideLoading()
              that.setData({
                showProductDetail: false
              })
              wx.showToast({
                title: '修改成功',
                icon: 'success',
                duration: 1500,
                success() {
                  setTimeout(() => {
                    that.initData()
                  }, 1500)
                }
              })
            } else {
              wx.hideLoading()
              cart.showMyTip({ _this: that, title: "服务器错误" })
            }
          })
        }
      }
    })
  },
  // 全选
  allChecked() {
    let data = this.data
    let allCheckedStatus = data.allCheckedStatus
    let unity = app.globalData.unity;

    this.setData({
      allCheckedStatus: allCheckedStatus ? false : true,
    })
    let ele = []
    let pay = 0
    let sum = 0
    unity.length = 0;
    data.allProducts.forEach((val, i) => {
      if (allCheckedStatus || val.soldOut == 1) {
        val.checked = false
        pay = 0
      } else {
        val.checked = true
        unity.push({ "id": val.goodsId, "specsName": val.specsName });
        pay += +val.goodsPrice * +val.goodsNum
        sum += val.goodsNum
      }
      ele.push(val)
    })
    this.setData({
      allProducts: ele,
      totalPay: this.returnFloat(pay),
      totalSum: sum
    })
  },

  onPullDownRefresh() {
    this.initData(() => {
      wx.stopPullDownRefresh()
    }, 'pulldown')
  },
  //保留两位小数
  returnFloat: function (value) {
    var value = Math.round(parseFloat(value) * 100) / 100;
    var xsd = value.toString().split(".");
    if (xsd.length == 1) {
      value = value.toString() + ".00";
      return value;
    }
    if (xsd.length > 1) {
      if (xsd[1].length < 2) {
        value = value.toString() + "0";
      }
      return value;
    }
  },
  //跳转到商品详情页面
  toProduct(e) {
    let id = cart.getDataSet(e, "id");
    let storeNo = this.data.userInfo.storeNo
    wx.navigateTo({
      url: '/pages/product/product?id=' + id + '&storeNo=' + storeNo
    })
  },
  showGoodImg(e) {
    let itemImg = cart.getDataSet(e, "goodspic");
    let list = [];
    list.push("" + itemImg);
    console.log("itemImg--------------------", itemImg, list);
    wx.previewImage({
      current: "" + itemImg, // 当前显示图片的http链接
      urls: list // 需要预览的图片http链接列表
    })
  }
})